package com.mediastory.spsserver.content.service.impl;

import java.io.File;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mediastory.spsserver.category.dao.CategoryDao;
import com.mediastory.spsserver.category.domain.Category;
import com.mediastory.spsserver.contFile.dao.ContFileDao;
import com.mediastory.spsserver.contFile.domain.ContFile;
import com.mediastory.spsserver.content.dao.ContentDao;
import com.mediastory.spsserver.content.domain.Content;
import com.mediastory.spsserver.content.service.ContentSvc;
import com.Ostermiller.util.Base64;

@Service
@Transactional
public class ContentSvcImpl implements ContentSvc {

	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	ContentDao contentDao;
	
	@Autowired
	ContFileDao contFileDao;
	
	@Autowired
	CategoryDao categoryDao;

	public ContentSvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<Content> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<Content>) (contentDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("contentList", (List<Content>) (contentDao.SelectList(condition)));
		resultMap.put("contentListTotalCnt", (Integer) (contentDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public Content findby(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return contentDao.select(condition);
	}

	@Override
	public Content add(Content content) throws Exception {
		// TODO Auto-generated method stub
		Content result = null;
		List<File> fileList = new Vector<File>();
		
		try {
			result = contentDao.insert(content);
			
			//파일 업로드
			MultipartFile cFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(content.getContFiles() != null){
				ContFile contFile = new ContFile();
				
				for(int i = 0;i<content.getContFiles().size();i++){
					cFile = content.getContFiles().get(i);
					
					fileType = content.getContFileTypes()[i];
					
					//파일의 크기가 0인 경우 넘긴다.(콘텐츠 URL로 넘긴경우 제외)
					if(cFile == null || cFile.getSize() == 0){
						continue;
					}
					
					
					fileData = content.getContFileDatas()[i];
					fileSize = cFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(content.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
					//업로드 경로
					String uploadDir = messages.getMessage("file.content.uploadDir") + content.getUserIdx() + "/";
					//viewUrl
					String viewUrl = messages.getMessage("file.content.viewUrl")  + content.getUserIdx() + "/";
					String fileNm = "";
					String url = "";					
					
					if(fileType.equals("mainImg")){
						if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
							fileNm = prefixNm + "_mainImg."+(cFile.getOriginalFilename()).split("\\.")[1];
						}
						fileData = "" + i;
					}else{
						continue;
					}
					
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					cFile.transferTo(file);
					
					fileList.add(file);

					//콘텐츠 파일 등록
					contFile.setContIdx(result.getIdx());
					contFile.setFileUrl(url);
					contFile.setFileSize(fileSize);
					contFile.setFileType(fileType);
					contFile.setFileData(fileData);
					contFileDao.insert(contFile);
				}
			}

			/*
			//disp order 등록
			if(content.getCategoryIdx() != null){
				Map<String, Object> condition = new HashMap<String, Object>();
				condition.put("cIdx", result.getcIdx());
				condition.put("contentIdx", result.getIdx());
				for (Integer categoryIdx : content.getCategoryIdx()) {
					condition.put("categoryIdx", categoryIdx);
					categoryDao.insertDispOrder(condition);
				}
			}	
			*/
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return result;
	}

	@Override
	public Content modify(Content content) throws Exception {
		// TODO Auto-generated method stub
		List<File> fileList = new Vector<File>();
		
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("contentIdx", content.getIdx());			
			
			//파일 업로드
			condition = new HashMap<String, Object>();
			condition.put("contIdx", content.getIdx());
			
			MultipartFile cFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(content.getContFiles() != null){
				ContFile contFile = new ContFile();
				
				for(int i = 0;i<content.getContFiles().size();i++){
					cFile = content.getContFiles().get(i);
					
					fileType = content.getContFileTypes()[i];

					//파일의 크기가 0인 경우 넘긴다.(콘텐츠 URL로 넘긴경우 제외)
					if(cFile == null || cFile.getSize() == 0){
						continue;
					}					

					fileData = content.getContFileDatas()[i];
					fileSize = cFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(content.getTitle(), "utf-8")+Long.toString(time))) + (1 + (int)(Math.random() * 100));
					//업로드 경로
					String uploadDir = messages.getMessage("file.content.uploadDir")  + content.getUserIdx() + "/";
					//viewUrl
					String viewUrl = messages.getMessage("file.content.viewUrl")  + content.getUserIdx()  + "/";
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("mainImg")){
						if(cFile != null && ! cFile.isEmpty() && cFile.getContentType().contains("image")){
							fileNm = prefixNm + "_mainImg."+(cFile.getOriginalFilename()).split("\\.")[1];
						}
						fileData = "" + i;
					}else{
						continue;
					}
					
					//콘텐츠파일 URL로 넘기는 경우					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					cFile.transferTo(file);
					
					fileList.add(file);					
					
					//콘텐츠 파일 등록
					contFile.setContIdx(content.getIdx());
					contFile.setFileUrl(url);
					contFile.setFileSize(fileSize);
					contFile.setFileType(fileType);
					contFile.setFileData(fileData);
					contFileDao.insert(contFile);
				}
			}
			
			//메인 이미지 삭제
			if(content.getContFileIdx() != null){
				condition = new HashMap<String, Object>();
				for(int contFileIdx : content.getContFileIdx()){
					condition.put("idx", contFileIdx);
					contFileDao.delete(condition);	
				}	
			}
			
			content = contentDao.update(content);
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return content;
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return contentDao.delete(condition);
	}

	@Override
	public Integer findbyChkNm(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return contentDao.SelectListTotalCnt(condition);
	}

}
